// Global variables
let trendChart = null;
let monthlyStatsChart = null;
let socket = null;
let statusFilter = '';
let startDate = '';
let endDate = '';
let lastReceivedData = null; // Store the last received data
let bankStatusVisible = false; // Track if bank status section is visible
let currentMonth = ''; // Current selected month for monthly stats
let monthlyViewMode = 'table'; // Current view mode for monthly stats: 'table' or 'chart'
const ChartDataLabels = window.ChartDataLabels; // 定义ChartDataLabels变量
let isLoading = false; // Track if a loading operation is in progress
let lastLoadingTime = 0; // Track when loading started

// Pagination variables
let currentPage = 1;
let pageSize = 10;
let totalPages = 1;
let allTasks = []; // Store all tasks before pagination

// Monthly stats pagination variables
let monthlyCurrentPage = 1;
let monthlyPageSize = 5; // 修改为每页显示5条
let monthlyTotalPages = 1;
let allMonthlyStats = []; // Store all monthly stats before pagination

// DOM elements
const successCount = document.getElementById('success-count');
const runningCount = document.getElementById('running-count');
const failedCount = document.getElementById('failed-count');
const lastUpdated = document.getElementById('last-updated');
const tasksBody = document.getElementById('tasks-body');
const statusFilterEl = document.getElementById('status-filter');
const startTimeEl = document.getElementById('start-time');
const endTimeEl = document.getElementById('end-time');
const applyTimeFilterBtn = document.getElementById('apply-time-filter');
const toggleBankStatusBtn = document.getElementById('toggle-bank-status');
const bankStatusSection = document.getElementById('bank-status-section');
const loadingDialog = document.getElementById('loading-dialog');

// Monthly stats DOM elements
const monthlyStartTimeEl = document.getElementById('monthly-start-time');
const monthlyEndTimeEl = document.getElementById('monthly-end-time');
const applyMonthlyTimeFilterBtn = document.getElementById('apply-monthly-time-filter');
const toggleMonthlyViewBtn = document.getElementById('toggle-monthly-view');
const monthlyStatsTableView = document.getElementById('monthly-stats-table-view');
const monthlyStatsChartView = document.getElementById('monthly-stats-chart-view');
const monthlyStatsBody = document.getElementById('monthly-stats-body');

// Monthly stats pagination DOM elements
const monthlyPrevPageBtn = document.getElementById('monthly-prev-page');
const monthlyNextPageBtn = document.getElementById('monthly-next-page');
const monthlyPageNumbersContainer = document.getElementById('monthly-page-numbers');
const monthlyPageSizeSelect = document.getElementById('monthly-page-size');
const monthlyShowingStart = document.getElementById('monthly-showing-start');
const monthlyShowingEnd = document.getElementById('monthly-showing-end');
const monthlyTotalRecords = document.getElementById('monthly-total-records');

// Pagination DOM elements
const prevPageBtn = document.getElementById('prev-page');
const nextPageBtn = document.getElementById('next-page');
const pageNumbersContainer = document.getElementById('page-numbers');
const pageSizeSelect = document.getElementById('page-size');
const showingStart = document.getElementById('showing-start');
const showingEnd = document.getElementById('showing-end');
const totalRecords = document.getElementById('total-records');

// Maximum number of data points to show on the chart
const MAX_CHART_POINTS = 12;

// Initialize the dashboard
document.addEventListener('DOMContentLoaded', function() {
    initializeWebSocket();
    initializeChart();
    initializeFilters();
    initializeToggleButton();
    initializePagination();
    initializeMonthlyStats();
    
    // Add global error handler to ensure loading dialog is always hidden
    window.addEventListener('error', function() {
        hideLoadingDialog();
    });
    
    // Add unhandled promise rejection handler
    window.addEventListener('unhandledrejection', function() {
        hideLoadingDialog();
    });
    
    // Force hide loading dialog when user interacts with the page
    document.addEventListener('click', function() {
        if (isLoading && Date.now() - lastLoadingTime > 10000) {
            // Only auto-hide if loading has been active for more than 10 seconds
            hideLoadingDialog();
        }
    });
});

// Initialize WebSocket connection
function initializeWebSocket() {
    // 使用固定的服务器IP地址
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';

    const config = window.APP_CONFIG;
    const wsUrl = `${protocol}//${config.websocketHost}:${config.websocketPort}/ws`;
    
    socket = new WebSocket(wsUrl);
    
    socket.onopen = function(event) {
        console.log('WebSocket connection established');
    };
    
    socket.onmessage = function(event) {
        const data = JSON.parse(event.data);
        lastReceivedData = data; // Store the last received data
        updateDashboard(data);
    };
    
    socket.onclose = function(event) {
        console.log('WebSocket connection closed');
        // Try to reconnect after 3 seconds
        setTimeout(initializeWebSocket, 3000);
    };
    
    socket.onerror = function(error) {
        console.error('WebSocket error:', error);
    };
}

// Initialize Chart.js
function initializeChart() {
    const ctx = document.getElementById('trend-chart').getContext('2d');
    
    trendChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [
                {
                    label: '成功',
                    data: [],
                    borderColor: '#10b981',
                    backgroundColor: 'rgba(16, 185, 129, 0.1)',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: true,
                    pointRadius: 4,
                    pointHoverRadius: 6,
                    pointBackgroundColor: '#10b981'
                },
                {
                    label: '运行中',
                    data: [],
                    borderColor: '#f59e0b',
                    backgroundColor: 'rgba(245, 158, 11, 0.1)',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: true,
                    pointRadius: 4,
                    pointHoverRadius: 6,
                    pointBackgroundColor: '#f59e0b'
                },
                {
                    label: '失败',
                    data: [],
                    borderColor: '#ef4444',
                    backgroundColor: 'rgba(239, 68, 68, 0.1)',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: true,
                    pointRadius: 4,
                    pointHoverRadius: 6,
                    pointBackgroundColor: '#ef4444'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        color: 'white',
                        font: {
                            size: 12
                        }
                    }
                },
                tooltip: {
                    enabled: true,
                    backgroundColor: 'rgba(0, 0, 0, 0.7)',
                    titleColor: 'white',
                    bodyColor: 'white',
                    borderColor: 'rgba(255, 255, 255, 0.2)',
                    borderWidth: 1,
                    padding: 10,
                    displayColors: true,
                    usePointStyle: true,
                    caretSize: 6,
                    caretPadding: 10,
                    cornerRadius: 6,
                    titleFont: {
                        size: 14,
                        weight: 'bold'
                    },
                    bodyFont: {
                        size: 13
                    },
                    boxPadding: 5,
                    position: 'nearest',
                    xAlign: 'center',
                    yAlign: 'bottom',
                    callbacks: {
                        title: function(tooltipItems) {
                            return '时间: ' + tooltipItems[0].label;
                        },
                        label: function(context) {
                            let label = context.dataset.label || '';
                            if (label) {
                                label += ': ';
                            }
                            if (context.parsed.y !== null) {
                                label += context.parsed.y;
                            }
                            return label;
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    },
                    ticks: {
                        color: 'rgba(255, 255, 255, 0.8)'
                    }
                },
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    },
                    ticks: {
                        color: 'rgba(255, 255, 255, 0.8)'
                    }
                }
            }
        }
    });
}

// Show loading dialog
let loadingDialogTimeout;
function showLoadingDialog(message = '处理中，请稍候...') {
    console.log('显示加载对话框: ' + message);
    
    // Prevent body scrolling to avoid layout shifts
    document.body.classList.add('loading-active');
    
    // Force any existing dialog to be hidden first
    loadingDialog.classList.remove('visible');
    
    // Use setTimeout to ensure the DOM has time to update
    setTimeout(() => {
        document.querySelector('.loading-dialog-text').textContent = message;
        loadingDialog.classList.add('visible');
        isLoading = true;
        lastLoadingTime = Date.now();
        
        // Clear any existing timeout
        if (loadingDialogTimeout) {
            clearTimeout(loadingDialogTimeout);
        }
        
        // Set a safety timeout to automatically hide the dialog after 30 seconds
        loadingDialogTimeout = setTimeout(() => {
            console.log('加载对话框超时自动关闭');
            hideLoadingDialog();
        }, 30000);
    }, 50); // Increased delay to ensure DOM stability
}

// Hide loading dialog
function hideLoadingDialog() {
    console.log('隐藏加载对话框');
    
    // Use setTimeout to prevent immediate hiding which can cause flickering
    setTimeout(() => {
        loadingDialog.classList.remove('visible');
        isLoading = false;
        
        // Clear the timeout
        if (loadingDialogTimeout) {
            clearTimeout(loadingDialogTimeout);
            loadingDialogTimeout = null;
        }
        
        // Restore body scrolling after a short delay to ensure smooth transition
        setTimeout(() => {
            document.body.classList.remove('loading-active');
        }, 300);
    }, 200); // Increased delay for smoother transition
}

// Initialize filters
function initializeFilters() {
    // Status filter
    statusFilterEl.addEventListener('change', function() {
        statusFilter = this.value;
        currentPage = 1; // Reset to first page when filter changes
        applyFilters();
    });
    
    // Set default dates
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const todayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
    
    startDate = formatDateTime(today);
    endDate = formatDateTime(todayEnd);
    
    // Initialize start time picker
    const startTimePicker = flatpickr(startTimeEl, {
        enableTime: true,
        noCalendar: false,
        dateFormat: 'Y-m-d H:i:S',
        time_24hr: true,
        defaultDate: today,
        locale: 'zh',
        appendTo: document.body,
        positionElement: startTimeEl,
        static: false,
        disableMobile: true,
        position: "auto"
    });
    
    // Initialize end time picker
    const endTimePicker = flatpickr(endTimeEl, {
        enableTime: true,
        noCalendar: false,
        dateFormat: 'Y-m-d H:i:S',
        time_24hr: true,
        defaultDate: todayEnd,
        locale: 'zh',
        appendTo: document.body,
        positionElement: endTimeEl,
        static: false,
        disableMobile: true,
        position: "auto"
    });
    
    // Apply time filter button
    applyTimeFilterBtn.addEventListener('click', function() {
        // Prevent multiple clicks
        if (isLoading) return;
        
        // Show loading dialog immediately
        showLoadingDialog('正在获取数据，请稍候...');
        
        const startDateTime = startTimePicker.selectedDates[0];
        const endDateTime = endTimePicker.selectedDates[0];
        
        if (startDateTime && endDateTime) {
            startDate = formatDateTime(startDateTime);
            endDate = formatDateTime(endDateTime);
            
            // Check if end date is after start date
            if (endDateTime < startDateTime) {
                hideLoadingDialog();
                alert('结束时间必须晚于开始时间');
                return;
            }
            
            currentPage = 1; // Reset to first page when filter changes
            
            // Show loading state on button
            showButtonLoading(applyTimeFilterBtn);
            
            // Fetch data with time range
            fetchTasksWithTimeRange(startDate, endDate);
        } else {
            hideLoadingDialog();
            alert('请选择开始时间和结束时间');
        }
    });
}

// Show loading state on button
function showButtonLoading(button) {
    button.classList.add('btn-loading');
    button.disabled = true;
}

// Hide loading state on button
function hideButtonLoading(button) {
    button.classList.remove('btn-loading');
    button.disabled = false;
}

// Format date to YYYY-MM-DD HH:MM:SS
function formatDateTime(date) {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
}

// Fetch tasks from API with time range filter
function fetchTasksWithTimeRange(startDate, endDate) {
    // Show loading state in table
    tasksBody.innerHTML = '<tr><td colspan="6" class="loading-message">加载中...<div class="loading-spinner"></div></td></tr>';
    
    // Prepare query parameters
    const queryParams = new URLSearchParams();
    if (statusFilter) {
        queryParams.append('status', statusFilter);
    }
    queryParams.append('start_date', startDate);
    queryParams.append('end_date', endDate);
    
    // Fetch data from API
    fetch(`/api/tasks?${queryParams.toString()}`)
        .then(response => response.json())
        .then(data => {
            // Store all tasks before pagination
            allTasks = data.tasks;
            
            // Update summary counts based on filtered tasks
            if (statusFilter) {
                // If filtering by status, update the summary to match the filtered count
                const filteredCount = allTasks.length;
                
                // Reset all counts to 0 first
                successCount.textContent = 0;
                runningCount.textContent = 0;
                failedCount.textContent = 0;
                
                // Then set the filtered status count
                switch(statusFilter) {
                    case '成功':
                        successCount.textContent = filteredCount;
                        break;
                    case '运行中':
                        runningCount.textContent = filteredCount;
                        break;
                    case '失败':
                        failedCount.textContent = filteredCount;
                        break;
                }
            } else {
                // If not filtering by status, count each status from the filtered tasks
                const success = allTasks.filter(task => task.status === '成功').length;
                const running = allTasks.filter(task => task.status === '运行中').length;
                const failed = allTasks.filter(task => task.status === '失败').length;
                
                // Update the summary counts
                successCount.textContent = success;
                runningCount.textContent = running;
                failedCount.textContent = failed;
            }
            
            // Update pagination info
            totalPages = Math.ceil(allTasks.length / pageSize);
            if (currentPage > totalPages) {
                currentPage = totalPages || 1;
            }
            
            // Render the current page
            renderPage();
            
            // Update page numbers
            renderPageNumbers();
            
            // Hide loading state on button
            hideButtonLoading(applyTimeFilterBtn);
            
            // Add minimum display time for loading dialog (at least 1 second)
            setTimeout(() => {
                // Hide loading dialog
                hideLoadingDialog();
            }, 1000);
        })
        .catch(error => {
            console.error('Error fetching tasks:', error);
            tasksBody.innerHTML = '<tr><td colspan="6" class="error-message">获取数据失败，请重试</td></tr>';
            
            // Hide loading state on button
            hideButtonLoading(applyTimeFilterBtn);
            
            // Hide loading dialog after delay
            setTimeout(() => {
                hideLoadingDialog();
            }, 1000);
        });
}

// Initialize pagination
function initializePagination() {
    // Page size change handler
    pageSizeSelect.addEventListener('change', function() {
        pageSize = parseInt(this.value);
        currentPage = 1; // Reset to first page when page size changes
        
        // Recalculate total pages
        totalPages = Math.ceil(allTasks.length / pageSize);
        
        // Render the current page
        renderPage();
        
        // Update page numbers
        renderPageNumbers();
    });
    
    // Previous page button
    prevPageBtn.addEventListener('click', function() {
        if (currentPage > 1) {
            currentPage--;
            renderPage();
            renderPageNumbers(); // Update page numbers when navigating
        }
    });
    
    // Next page button
    nextPageBtn.addEventListener('click', function() {
        if (currentPage < totalPages) {
            currentPage++;
            renderPage();
            renderPageNumbers(); // Update page numbers when navigating
        }
    });
}

// Apply filters to the last received data instead of fetching from API
function applyFilters() {
    if (!lastReceivedData) return;
    
    // Filter the bank tasks based on the selected filters
    let filteredTasks = lastReceivedData.rpa_tasks;
    
    if (statusFilter) {
        filteredTasks = filteredTasks.filter(task => task.status === statusFilter);
    }
    
    // For date filtering, we would need to parse the dates and compare
    // This is simplified for now
    
    // Store all filtered tasks before pagination
    allTasks = filteredTasks;
    
    // Update summary counts based on filtered tasks
    if (statusFilter) {
        // If filtering by status, update the summary to match the filtered count
        const filteredCount = filteredTasks.length;
        
        // Reset all counts to 0 first
        successCount.textContent = 0;
        runningCount.textContent = 0;
        failedCount.textContent = 0;
        
        // Then set the filtered status count
        switch(statusFilter) {
            case '成功':
                successCount.textContent = filteredCount;
                break;
            case '运行中':
                runningCount.textContent = filteredCount;
                break;
            case '失败':
                failedCount.textContent = filteredCount;
                break;
        }
    } else {
        // If not filtering by status, count each status from the filtered tasks
        const success = filteredTasks.filter(task => task.status === '成功').length;
        const running = filteredTasks.filter(task => task.status === '运行中').length;
        const failed = filteredTasks.filter(task => task.status === '失败').length;
        
        // Update the summary counts
        successCount.textContent = success;
        runningCount.textContent = running;
        failedCount.textContent = failed;
    }
    
    // Update pagination info
    totalPages = Math.ceil(allTasks.length / pageSize);
    if (currentPage > totalPages) {
        currentPage = totalPages || 1;
    }
    
    // Render the current page
    renderPage();
}

// Render the current page of tasks
function renderPage() {
    // Calculate start and end indices for current page
    const startIdx = (currentPage - 1) * pageSize;
    const endIdx = Math.min(startIdx + pageSize, allTasks.length);
    
    // Get tasks for current page
    const tasksForPage = allTasks.slice(startIdx, endIdx);
    
    // Update tasks table with paginated data
    updateTasksTable(tasksForPage);
    
    // Update pagination UI
    updatePaginationUI(startIdx, endIdx);
}

// Update pagination UI elements
function updatePaginationUI(startIdx, endIdx) {
    // Update showing info
    showingStart.textContent = allTasks.length > 0 ? startIdx + 1 : 0;
    showingEnd.textContent = endIdx;
    totalRecords.textContent = allTasks.length;
    
    // Update page number buttons
    renderPageNumbers();
    
    // Update prev/next buttons state
    prevPageBtn.disabled = currentPage === 1;
    nextPageBtn.disabled = currentPage === totalPages || totalPages === 0;
}

// Render page number buttons
function renderPageNumbers() {
    pageNumbersContainer.innerHTML = '';
    
    // Determine range of page numbers to show
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);
    
    // Adjust start if we're near the end
    if (endPage - startPage < 4 && totalPages > 4) {
        if (currentPage > totalPages - 2) {
            // Near the end, show last 5 pages
            endPage = totalPages;
            startPage = Math.max(1, totalPages - 4);
        } else if (currentPage < 3) {
            // Near the beginning, show first 5 pages
            startPage = 1;
            endPage = Math.min(totalPages, 5);
        }
    }
    
    // Add first page if not included
    if (startPage > 1) {
        addPageNumberButton(1);
        if (startPage > 2) {
            addEllipsis();
        }
    }
    
    // Add page numbers
    for (let i = startPage; i <= endPage; i++) {
        addPageNumberButton(i);
    }
    
    // Add last page if not included
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            addEllipsis();
        }
        addPageNumberButton(totalPages);
    }
}

// Add a page number button
function addPageNumberButton(pageNum) {
    const pageButton = document.createElement('div');
    pageButton.className = 'page-number' + (pageNum === currentPage ? ' active' : '');
    pageButton.textContent = pageNum;
    pageButton.addEventListener('click', function() {
        currentPage = pageNum;
        renderPage();
    });
    pageNumbersContainer.appendChild(pageButton);
}

// Add ellipsis to page numbers
function addEllipsis() {
    const ellipsis = document.createElement('div');
    ellipsis.className = 'page-ellipsis';
    ellipsis.textContent = '...';
    pageNumbersContainer.appendChild(ellipsis);
}

// Update dashboard with WebSocket data
function updateDashboard(data) {
    // Update summary cards
    successCount.textContent = data.summary.success;
    runningCount.textContent = data.summary.running;
    failedCount.textContent = data.summary.failed;
    
    // Update last updated time
    lastUpdated.textContent = data.timestamp;
    
    // Update chart data
    updateChart(data.time_series);
    
    // Always update the tasks table with real-time data
    // If filters are applied, apply them to the new data
    if (statusFilter || (startDate && startDate !== '') || (endDate && endDate !== '')) {
        applyFilters();
    } else {
        // Store all tasks before pagination
        allTasks = data.rpa_tasks;
        
        // Update pagination info
        totalPages = Math.ceil(allTasks.length / pageSize);
        if (currentPage > totalPages) {
            currentPage = totalPages || 1;
        }
        
        // Render the current page
        renderPage();
    }
}

// Update chart with new data
function updateChart(timeSeriesData) {
    // Get only the last MAX_CHART_POINTS data points if we have more
    const displayData = timeSeriesData.slice(-MAX_CHART_POINTS);
    
    // Extract data for chart
    const labels = displayData.map(item => item.time);
    const successData = displayData.map(item => item.success);
    const runningData = displayData.map(item => item.running);
    const failedData = displayData.map(item => item.failed);
    
    // Update chart data
    trendChart.data.labels = labels;
    trendChart.data.datasets[0].data = successData;
    trendChart.data.datasets[1].data = runningData;
    trendChart.data.datasets[2].data = failedData;
    
    // Force redraw with animation to ensure tooltips work properly
    trendChart.update('active');
}

// Update tasks table
function updateTasksTable(tasks) {
    // Clear existing rows
    tasksBody.innerHTML = '';
    
    // Add new rows
    tasks.forEach(task => {
        const row = document.createElement('tr');
        
        // Determine status class
        let statusClass = '';
        switch (task.status) {
            case '成功':
                statusClass = 'status-success';
                break;
            case '运行中':
                statusClass = 'status-running';
                break;
            case '失败':
                statusClass = 'status-failed';
                break;
        }
        
        // Create row HTML
        row.innerHTML = `
            <td>${task.app_name}</td>
            <td><span class="status ${statusClass}">${task.status}</span></td>
            <td>${task.start_time}</td>
            <td>${task.end_time}</td>
            <td>${task.duration}</td>
            <td>${task.error_reason}</td>
        `;
        
        tasksBody.appendChild(row);
    });
}

// Initialize toggle button
function initializeToggleButton() {
    toggleBankStatusBtn.addEventListener('click', function() {
        bankStatusVisible = !bankStatusVisible;
        
        if (bankStatusVisible) {
            bankStatusSection.style.display = 'block';
            toggleBankStatusBtn.innerHTML = '<i class="icon">📊</i> 隐藏执行详情';
            toggleBankStatusBtn.classList.add('active');
            
            // If we have data, make sure the table is updated
            if (lastReceivedData) {
                applyFilters();
            }
        } else {
            bankStatusSection.style.display = 'none';
            toggleBankStatusBtn.innerHTML = '<i class="icon">📊</i> RPA执行详情';
            toggleBankStatusBtn.classList.remove('active');
        }
    });
}

// Initialize monthly stats
function initializeMonthlyStats() {
    // Set current month as default
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonthNum = now.getMonth() + 1;
    currentMonth = `${currentYear}-${String(currentMonthNum).padStart(2, '0')}`;
    
    // Get first and last day of current month
    const firstDay = new Date(currentYear, currentMonthNum - 1, 1);
    const lastDay = new Date(currentYear, currentMonthNum, 0, 23, 59, 59);
    
    // Initialize monthly start time picker
    const monthlyStartTimePicker = flatpickr(monthlyStartTimeEl, {
        enableTime: true,
        noCalendar: false,
        dateFormat: 'Y-m-d H:i:S',
        time_24hr: true,
        defaultDate: firstDay,
        locale: 'zh',
        appendTo: document.body,
        positionElement: monthlyStartTimeEl,
        static: false,
        disableMobile: true,
        position: "auto"
    });
    
    // Initialize monthly end time picker
    const monthlyEndTimePicker = flatpickr(monthlyEndTimeEl, {
        enableTime: true,
        noCalendar: false,
        dateFormat: 'Y-m-d H:i:S',
        time_24hr: true,
        defaultDate: lastDay,
        locale: 'zh',
        appendTo: document.body,
        positionElement: monthlyEndTimeEl,
        static: false,
        disableMobile: true,
        position: "auto"
    });
    
    // Apply monthly time filter button
    applyMonthlyTimeFilterBtn.addEventListener('click', function() {
        // Prevent multiple clicks
        if (isLoading) return;
        
        // Show loading dialog immediately
        showLoadingDialog('正在获取月度统计数据，请稍候...');
        
        const startDateTime = monthlyStartTimePicker.selectedDates[0];
        const endDateTime = monthlyEndTimePicker.selectedDates[0];
        
        if (startDateTime && endDateTime) {
            const startDateFormatted = formatDateTime(startDateTime);
            const endDateFormatted = formatDateTime(endDateTime);
            
            // Check if end date is after start date
            if (endDateTime < startDateTime) {
                hideLoadingDialog();
                alert('结束时间必须晚于开始时间');
                return;
            }
            
            // Show loading state on button
            showButtonLoading(applyMonthlyTimeFilterBtn);
            
            // Fetch monthly stats with the selected time range
            fetchMonthlyStatsWithTimeRange(startDateFormatted, endDateFormatted);
        } else {
            hideLoadingDialog();
            alert('请选择开始时间和结束时间');
        }
    });
    
    // Initialize toggle button for view mode
    toggleMonthlyViewBtn.innerHTML = '<i class="icon">📊</i> <span class="btn-text">图表视图</span>';
    toggleMonthlyViewBtn.addEventListener('click', function() {
        toggleMonthlyViewMode();
    });
    
    // Initialize monthly pagination controls
    initializeMonthlyPagination();
    
    // Fetch initial monthly stats for current month
    const startDateFormatted = formatDateTime(firstDay);
    const endDateFormatted = formatDateTime(lastDay);
    fetchMonthlyStatsWithTimeRange(startDateFormatted, endDateFormatted);
}

// Fetch monthly stats with time range from the API
function fetchMonthlyStatsWithTimeRange(startDate, endDate) {
    // Show loading state
    monthlyStatsBody.innerHTML = '<tr><td colspan="5" class="loading-message">加载中...<div class="loading-spinner"></div></td></tr>';
    
    // Prepare query parameters
    const queryParams = new URLSearchParams();
    queryParams.append('start_date', startDate);
    queryParams.append('end_date', endDate);
    
    fetch(`/api/monthly-stats?${queryParams.toString()}`)
        .then(response => response.json())
        .then(data => {
            updateMonthlyStatsView(data);
            
            // Hide loading state on button
            hideButtonLoading(applyMonthlyTimeFilterBtn);
            
            // Add minimum display time for loading dialog (at least 1 second)
            setTimeout(() => {
                // Hide loading dialog
                hideLoadingDialog();
            }, 1000);
        })
        .catch(error => {
            console.error('Error fetching monthly stats:', error);
            monthlyStatsBody.innerHTML = '<tr><td colspan="5" class="error-message">获取数据失败，请重试</td></tr>';
            
            // Hide loading state on button
            hideButtonLoading(applyMonthlyTimeFilterBtn);
            
            // Hide loading dialog after delay
            setTimeout(() => {
                hideLoadingDialog();
            }, 1000);
        });
}

// Fetch monthly stats from the API
function fetchMonthlyStats(month) {
    fetch(`/api/monthly-stats?month=${month}`)
        .then(response => response.json())
        .then(data => {
            updateMonthlyStatsView(data);
        })
        .catch(error => {
            console.error('Error fetching monthly stats:', error);
            monthlyStatsBody.innerHTML = '<tr><td colspan="5" class="error-message">获取数据失败，请重试</td></tr>';
        });
}

// Initialize monthly pagination
function initializeMonthlyPagination() {
    // Page size change handler
    monthlyPageSizeSelect.addEventListener('change', function() {
        monthlyPageSize = parseInt(this.value);
        monthlyCurrentPage = 1; // Reset to first page when page size changes
        
        // Recalculate total pages
        monthlyTotalPages = Math.ceil(allMonthlyStats.length / monthlyPageSize);
        
        // Re-render with new page size
        if (monthlyViewMode === 'table') {
            renderMonthlyPage();
        } else {
            renderMonthlyStatsChart(allMonthlyStats);
        }
        
        // Update page numbers
        renderMonthlyPageNumbers();
    });
    
    // Previous page button
    monthlyPrevPageBtn.addEventListener('click', function() {
        if (monthlyCurrentPage > 1) {
            monthlyCurrentPage--;
            
            if (monthlyViewMode === 'table') {
                renderMonthlyPage();
            } else {
                renderMonthlyStatsChart(allMonthlyStats);
            }
            
            renderMonthlyPageNumbers(); // Update page numbers when navigating
        }
    });
    
    // Next page button
    monthlyNextPageBtn.addEventListener('click', function() {
        if (monthlyCurrentPage < monthlyTotalPages) {
            monthlyCurrentPage++;
            
            if (monthlyViewMode === 'table') {
                renderMonthlyPage();
            } else {
                renderMonthlyStatsChart(allMonthlyStats);
            }
            
            renderMonthlyPageNumbers(); // Update page numbers when navigating
        }
    });
}

// Update monthly stats view based on current mode
function updateMonthlyStatsView(data) {
    if (monthlyViewMode === 'table') {
        renderMonthlyStatsTable(data.stats);
    } else {
        renderMonthlyStatsChart(data.stats);
    }
}

// Render monthly stats table
function renderMonthlyStatsTable(stats) {
    // Store all stats for pagination
    allMonthlyStats = [...stats];
    
    // Sort stats by success_rate in descending order
    allMonthlyStats.sort((a, b) => b.success_rate - a.success_rate);
    
    // Update total records count
    monthlyTotalRecords.textContent = allMonthlyStats.length;
    
    // Calculate total pages
    monthlyTotalPages = Math.ceil(allMonthlyStats.length / monthlyPageSize);
    
    // Ensure current page is valid
    if (monthlyCurrentPage > monthlyTotalPages) {
        monthlyCurrentPage = monthlyTotalPages || 1;
    }
    
    // Render the current page
    renderMonthlyPage();
    
    // Update pagination UI
    renderMonthlyPageNumbers();
}

// Render the current page of monthly stats
function renderMonthlyPage() {
    // Clear existing table rows
    monthlyStatsBody.innerHTML = '';
    
    // Calculate start and end indices for the current page
    const startIdx = (monthlyCurrentPage - 1) * monthlyPageSize;
    const endIdx = Math.min(startIdx + monthlyPageSize, allMonthlyStats.length);
    
    // Get the current page's data
    const currentPageData = allMonthlyStats.slice(startIdx, endIdx);
    
    // Add rows for each RPA in the current page
    currentPageData.forEach(rpa => {
        const row = document.createElement('tr');
        
        // Determine success rate class
        let successRateClass = 'success-rate-high';
        if (rpa.success_rate < 90) {
            successRateClass = 'success-rate-medium';
        }
        if (rpa.success_rate < 80) {
            successRateClass = 'success-rate-low';
        }
        
        row.innerHTML = `
            <td>${rpa.rpa_name}</td>
            <td>${rpa.success_count}</td>
            <td>${rpa.failed_count}</td>
            <td>${rpa.total_count}</td>
            <td><span class="${successRateClass}">${rpa.success_rate}%</span></td>
        `;
        
        monthlyStatsBody.appendChild(row);
    });
    
    // Update pagination UI
    updateMonthlyPaginationUI(startIdx, endIdx);
    
    // 更新页码高亮
    updateMonthlyPageNumbersHighlight();
}

// 更新月度统计页码高亮
function updateMonthlyPageNumbersHighlight() {
    const pageButtons = monthlyPageNumbersContainer.querySelectorAll('.page-number');
    pageButtons.forEach(btn => {
        btn.classList.remove('active');
        if (parseInt(btn.textContent) === monthlyCurrentPage) {
            btn.classList.add('active');
        }
    });
}

// Update monthly pagination UI
function updateMonthlyPaginationUI(startIdx, endIdx) {
    // Update showing start and end
    monthlyShowingStart.textContent = allMonthlyStats.length > 0 ? startIdx + 1 : 0;
    monthlyShowingEnd.textContent = endIdx;
    
    // Enable/disable previous and next buttons
    monthlyPrevPageBtn.disabled = monthlyCurrentPage <= 1;
    monthlyNextPageBtn.disabled = monthlyCurrentPage >= monthlyTotalPages;
}

// Render monthly page numbers
function renderMonthlyPageNumbers() {
    // Clear existing page numbers
    monthlyPageNumbersContainer.innerHTML = '';
    
    // Don't show page numbers if there's only one page
    if (monthlyTotalPages <= 1) return;
    
    // Determine which page numbers to show
    let startPage = Math.max(1, monthlyCurrentPage - 2);
    let endPage = Math.min(monthlyTotalPages, monthlyCurrentPage + 2);
    
    // Adjust if we're near the end
    if (endPage - startPage < 4 && monthlyTotalPages > 4) {
        if (monthlyCurrentPage > monthlyTotalPages - 2) {
            // Near the end, show last 5 pages
            endPage = monthlyTotalPages;
            startPage = Math.max(1, monthlyTotalPages - 4);
        } else if (monthlyCurrentPage < 3) {
            // Near the beginning, show first 5 pages
            startPage = 1;
            endPage = Math.min(monthlyTotalPages, 5);
        }
    }
    
    // Add first page and ellipsis if needed
    if (startPage > 1) {
        addMonthlyPageNumberButton(1);
        if (startPage > 2) {
            addMonthlyEllipsis();
        }
    }
    
    // Add page numbers
    for (let i = startPage; i <= endPage; i++) {
        addMonthlyPageNumberButton(i);
    }
    
    // Add ellipsis and last page if needed
    if (endPage < monthlyTotalPages) {
        if (endPage < monthlyTotalPages - 1) {
            addMonthlyEllipsis();
        }
        addMonthlyPageNumberButton(monthlyTotalPages);
    }
}

// Add a page number button to the monthly pagination
function addMonthlyPageNumberButton(pageNum) {
    const pageButton = document.createElement('div');
    pageButton.className = 'page-number' + (pageNum === monthlyCurrentPage ? ' active' : '');
    pageButton.textContent = pageNum;
    pageButton.addEventListener('click', function() {
        monthlyCurrentPage = pageNum;
        renderMonthlyPage();
        // 页码高亮已在renderMonthlyPage中处理
    });
    monthlyPageNumbersContainer.appendChild(pageButton);
}

// Add ellipsis to the monthly pagination
function addMonthlyEllipsis() {
    const ellipsis = document.createElement('div');
    ellipsis.className = 'page-ellipsis';
    ellipsis.textContent = '...';
    monthlyPageNumbersContainer.appendChild(ellipsis);
}

// Render monthly stats chart
function renderMonthlyStatsChart(stats) {
    // Store all stats for pagination
    allMonthlyStats = [...stats];
    
    // Sort stats by total_count in descending order
    allMonthlyStats.sort((a, b) => b.total_count - a.total_count);
    
    // Update total records count
    monthlyTotalRecords.textContent = allMonthlyStats.length;
    
    // Calculate total pages
    monthlyTotalPages = Math.ceil(allMonthlyStats.length / monthlyPageSize);
    
    // Ensure current page is valid
    if (monthlyCurrentPage > monthlyTotalPages) {
        monthlyCurrentPage = monthlyTotalPages || 1;
    }
    
    // Calculate start and end indices for the current page
    const startIdx = (monthlyCurrentPage - 1) * monthlyPageSize;
    const endIdx = Math.min(startIdx + monthlyPageSize, allMonthlyStats.length);
    
    // Get the current page's data
    const currentPageData = allMonthlyStats.slice(startIdx, endIdx);
    
    // Prepare data for chart - only use current page data
    const rpaNames = currentPageData.map(item => item.rpa_name);
    const successCounts = currentPageData.map(item => item.success_count);
    const failedCounts = currentPageData.map(item => item.failed_count);
    const successRates = currentPageData.map(item => item.success_rate);
    
    // Destroy existing chart if it exists
    if (monthlyStatsChart) {
        monthlyStatsChart.destroy();
    }
    
    // Create new chart
    const ctx = document.getElementById('monthly-stats-chart').getContext('2d');
    monthlyStatsChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: rpaNames,
            datasets: [
                {
                    label: '成功',
                    data: successCounts,
                    backgroundColor: 'rgba(16, 185, 129, 0.7)',
                    borderColor: '#10b981',
                    borderWidth: 1,
                    borderRadius: 4,
                    barPercentage: 0.6,
                    categoryPercentage: 0.8
                },
                {
                    label: '失败',
                    data: failedCounts,
                    backgroundColor: 'rgba(239, 68, 68, 0.7)',
                    borderColor: '#ef4444',
                    borderWidth: 1,
                    borderRadius: 4,
                    barPercentage: 0.6,
                    categoryPercentage: 0.8
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            layout: {
                padding: {
                    top: 30, // 增加顶部填充以容纳数据标签
                    right: 25,
                    bottom: 20,
                    left: 25
                }
            },
            plugins: {
                legend: {
                    position: 'top',
                    align: 'end',
                    labels: {
                        color: 'white',
                        usePointStyle: true,
                        pointStyle: 'circle',
                        padding: 20,
                        font: {
                            size: 12
                        }
                    }
                },
                tooltip: {
                    enabled: true,
                    backgroundColor: 'rgba(0, 0, 0, 0.7)',
                    titleColor: 'white',
                    bodyColor: 'white',
                    padding: 12,
                    cornerRadius: 8,
                    callbacks: {
                        label: function(context) {
                            const label = context.dataset.label || '';
                            return `${label}: ${context.parsed.y}`;
                        },
                        afterBody: function(tooltipItems) {
                            const dataIndex = tooltipItems[0].dataIndex;
                            return `成功率: ${successRates[dataIndex]}%`;
                        }
                    }
                },
                // 添加数据标签插件
                datalabels: {
                    display: true,
                    color: 'white',
                    font: {
                        weight: 'bold',
                        size: 11
                    },
                    formatter: (value) => value,
                    anchor: 'end',
                    align: 'top',
                    offset: 0
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false,
                        color: 'rgba(255, 255, 255, 0.1)'
                    },
                    ticks: {
                        color: 'rgba(255, 255, 255, 0.8)',
                        font: {
                            size: 11
                        },
                        maxRotation: 45,
                        minRotation: 45,
                        autoSkip: false // 确保所有标签都显示
                    }
                },
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    },
                    ticks: {
                        color: 'rgba(255, 255, 255, 0.8)',
                        font: {
                            size: 11
                        },
                        padding: 10
                    }
                }
            }
        },
        plugins: [ChartDataLabels] // 使用ChartDataLabels插件
    });
    
    // Update pagination UI
    updateMonthlyPaginationUI(startIdx, endIdx);
    
    // Update page numbers
    renderMonthlyPageNumbers();
}

// Toggle monthly stats view mode between table and chart
function toggleMonthlyViewMode() {
    if (monthlyViewMode === 'table') {
        monthlyViewMode = 'chart';
        monthlyStatsTableView.style.display = 'none';
        monthlyStatsChartView.style.display = 'block';
        toggleMonthlyViewBtn.innerHTML = '<i class="icon">📋</i> <span class="btn-text">表格视图</span>';
        toggleMonthlyViewBtn.classList.add('active');
        
        // Use the current page data for chart
        if (allMonthlyStats.length > 0) {
            renderMonthlyStatsChart(allMonthlyStats);
        }
    } else {
        monthlyViewMode = 'table';
        monthlyStatsTableView.style.display = 'block';
        monthlyStatsChartView.style.display = 'none';
        toggleMonthlyViewBtn.innerHTML = '<i class="icon">📊</i> <span class="btn-text">图表视图</span>';
        toggleMonthlyViewBtn.classList.remove('active');
        
        // Maintain the current page in table view
        renderMonthlyPage();
    }
} 